import Router from '@koa/router';
import sequelize from '../config/db.js';
const router = new Router({ prefix: '/api' });
import { auth } from '../middlewares/auth.js';
// 统一的错误响应结构
const errorResponse = (code, message) => ({
  code,
  message,
  data: null
});

// 统一的成功响应结构
const successResponse = (data, meta = null) => ({
  code: 'SUCCESS',
  message: '操作成功',
  data,
  meta
});

// 工具函数：平铺数据转树形
function buildFavoriteTree(favorites) {
  const map = new Map();
  const tree = [];
  favorites.forEach(favorite => {
    favorite.children = [];
    map.set(favorite.id, favorite);
    if (favorite.parent_id === null) {
      tree.push(favorite);
    } else {
      const parent = map.get(favorite.parent_id);
      parent.children.push(favorite);
    }
  });
  return tree;
}

// GET /api/favorites/tree?user_id=1
router.get('/favorites/tree',auth, async (ctx) => {
  try {
    const {userId:user_id} = ctx.state.user;
    console.log('%c [ user_id ]-41', 'font-size:13px; background:pink; color:#bf2c9f;', user_id)
    const query = `
    SELECT
    *
    FROM
    user_favorites
    WHERE
        user_id = '${user_id}'
        ORDER BY
        created_at ASC;
        `;
    const favorites = await sequelize.query(query, {
      replacements: { user_id },
      type: sequelize.QueryTypes.SELECT,
    });
    console.log('%c [ favorites ]-52', 'font-size:13px; background:pink; color:#bf2c9f;', favorites)
    if (!favorites.length) {
      ctx.body = successResponse([]);
    } else {
      const data = buildFavoriteTree(favorites);
      ctx.body = successResponse(data);
    }
  } catch (err) {
    console.error('查询失败:', err);
    ctx.status = 500;
    ctx.body = errorResponse('INTERNAL_ERROR', '服务器内部错误');
  }
});

router.post('/favorites', auth, async (ctx) => {
  try {
    const { name, parent_id, is_default, sort_order, content_id, content_type } = ctx.request.body;
    const { userId: user_id } = ctx.state.user;

    // 数据校验
    if (!name) {
      ctx.status = 400;
      ctx.body = errorResponse('NAME_REQUIRED', '收藏夹名称不能为空');
      return;
    }
    if (!content_id || !content_type) {
      ctx.status = 400;
      ctx.body = errorResponse('CONTENT_REQUIRED', '内容ID和内容类型不能为空');
      return;
    }

    console.log('%c [  user_id, name, parent_id, is_default, sort_order, content_id, content_type ]-92', 'font-size:13px; background:pink; color:#bf2c9f;',  user_id, name, parent_id, is_default, sort_order, content_id, content_type)
    // 创建收藏夹
    const favorite = await sequelize.query(
      `INSERT INTO user_favorites (user_id, name, parent_id, is_default, sort_order,content_id, content_type) VALUES (:user_id, :name, :parent_id, :is_default, :sort_order, :content_id, :content_type)`,
      {
        replacements: { user_id, name, parent_id, is_default, sort_order, content_id, content_type},
        type: sequelize.QueryTypes.INSERT,
      }
    );
    console.log('%c [ favorite ]-90', 'font-size:13px; background:pink; color:#bf2c9f;', favorite)

    ctx.body = successResponse({ message: '收藏夹创建成功', favorite_id: favorite[0]  });
  } catch (err) {
    console.error('添加收藏失败:', err);
    ctx.status = 500;
    ctx.body = errorResponse('INTERNAL_ERROR', '服务器内部错误');
  }
});

// DELETE /api/favorites/:favorite_id
router.post('/unfavorite/:content_id', auth, async (ctx) => {
  try {
    const { content_id } = ctx.params;
    console.log('%c [ content_id ]-110', 'font-size:13px; background:pink; color:#bf2c9f;', content_id)
    const { userId: user_id } = ctx.state.user;

    // 检查收藏夹是否存在且属于当前用户
    const favorite = await sequelize.query(
      `SELECT * FROM user_favorites WHERE content_id = :content_id AND user_id = :user_id`,
      {
        replacements: { content_id, user_id },
        type: sequelize.QueryTypes.SELECT,
      }
    );

    if (!favorite.length) {
      ctx.status = 404;
      ctx.body = errorResponse('FAVORITE_NOT_FOUND', '收藏夹不存在或不属于当前用户');
      return;
    }



    await sequelize.query(
      `DELETE FROM user_favorites WHERE content_id = :content_id AND user_id = :user_id`,
      {
        replacements: { content_id,user_id },
        type: sequelize.QueryTypes.DELETE,
      }
    );

    ctx.body = successResponse({ message: '取消收藏成功' });
  } catch (err) {
    console.error('取消收藏失败:', err);
    ctx.status = 500;
    ctx.body = errorResponse('INTERNAL_ERROR', '服务器内部错误');
  }
});

// GET /api/favorites/check?content_id=123&content_type=1
router.get('/favorites/check', auth, async (ctx) => {
  try {
    const { content_id, content_type = '1' } = ctx.query;
    const { userId: user_id } = ctx.state.user;

    // 数据校验
    if (!content_id || !content_type) {
      ctx.status = 400;
      ctx.body = errorResponse('CONTENT_REQUIRED', '内容ID和内容类型不能为空');
      return;
    }

    // 查询是否已收藏
    const query = `
      SELECT
        *
      FROM
        user_favorites

      WHERE
        user_favorites.user_id = :user_id
        AND user_favorites.content_id = :content_id
        AND user_favorites.content_type = :content_type;
    `;
    console.log('%c [ user_id, content_id, content_type ]-181', 'font-size:13px; background:pink; color:#bf2c9f;', user_id, content_id, content_type)
    const result = await sequelize.query(query, {
      replacements: { user_id, content_id, content_type },
      type: sequelize.QueryTypes.SELECT,
    });

    if (result.length > 0) {
      ctx.body = successResponse({ is_favorited: true, favorite: result[0] });
    } else {
      ctx.body = successResponse({ is_favorited: false });
    }
  } catch (err) {
    console.error('查询收藏状态失败:', err);
    ctx.status = 500;
    ctx.body = errorResponse('INTERNAL_ERROR', '服务器内部错误');
  }
});
export default router;